<!-- @format -->

<template>
  <section class="todoapp">
    <!-- 使用组件 -->
    <TodoHeader @add-todo="addTodo" />
    <TodoMain
      :arr="todoList"
      @del-todo="delTodo" />
    <TodoFooter
      :arr="todoList"
      @clear-todo="clearTodo" />
  </section>
</template>

<script>
  // 从 styles 目录下导入相关样式
  import './styles/base.css'
  import './styles/index.css'

  // 导入组件
  import TodoHeader from './components/TodoHeader.vue'
  import TodoMain from './components/TodoMain.vue'
  import TodoFooter from './components/TodoFooter.vue'
  export default {
    name: 'App',
    // 注册组件
    components: {
      TodoHeader,
      TodoMain,
      TodoFooter
    },
    data() {
      return {
        // 待办任务列表
        todoList: JSON.parse(localStorage.getItem('todo-list')) || [
          { id: 100, name: '抽烟', done: true },
          { id: 101, name: '喝酒', done: true },
          { id: 102, name: '改bug', done: false }
        ]
      }
    },
    watch: {
      todoList: {
        deep: true,
        handler(newVal) {
          localStorage.setItem('todo-list', JSON.stringify(newVal))
        }
      }
    },
    methods: {
      // 添加todo
      addTodo(name) {
        const id = this.todoList.length
          ? this.todoList[this.todoList.length - 1].id + 1
          : 100

        this.todoList.push({
          id,
          name,
          done: false
        })
      },
      // 删除todo
      delTodo(i) {
        this.todoList.splice(i, 1)
      },
      // 清空todo
      clearTodo() {
        this.todoList = this.todoList.filter(({ done }) => !done)
      }
    }
  }
</script>
